import { BlockchainNodeConfigType, ConfigType } from "./config.type";
import fs from "fs";
import { BlockchainService } from "./blockchain/BlockchainService";
import { ExplorerService } from "./explorer/ExplorerService";
import path from "path";
import ejs from "ejs";
import { BridgeService } from "./bridge/BridgeService";

export class CreateService {
    blockchainService: BlockchainService;
    explorerService: ExplorerService;
    bridgeService: BridgeService;

    constructor(private config: ConfigType, private exportPath: string) {
        this.bridgeService = new BridgeService(this.config.bridge, this.exportPath);
        this.blockchainService = new BlockchainService(this.exportPath, this.config.blockchain, this.bridgeService);
        this.explorerService = new ExplorerService(this.exportPath);
    }

    async create() {
        if (!this.config.bridge.xrplAddress) {
            await this.bridgeService.createXrpBridge();
        }
        const nodes = this.blockchainService.configure();
        const evmRpc = `http://${nodes[0].host}`;
        this.explorerService.configure(evmRpc);
        await this.bridgeService.configure(`${evmRpc}:8545`);
        this.export(nodes);
    }

    export(nodes: BlockchainNodeConfigType[]) {
        const template = fs.readFileSync(path.join(__dirname, "./template/docker-compose.yml.ejs")).toString();
        const result = ejs.render(template, {
            nodes,
            dockerImage: this.blockchainService.dockerImage,
            enableExplorer: !this.config.explorer.disable,
            witnesses: this.config.bridge.witnesses,
        });
        fs.writeFileSync(path.join(this.exportPath, "docker-compose.yml"), result);
    }
}
